import java.util.*;

public class NextMaxElement {

    public int[] maxElemant(int[] nums1,int[] nums2){
        int[] res=new int[nums1.length];
        for (int i = 0; i <nums1.length ; i++) {
            boolean flag=false;
            for (int j = 0; j <nums2.length ; j++) {
                if(nums1[i]==nums2[j]){
                    flag=true;
                }
                if(flag&&nums2[j]>nums1[i]){
                    res[i]=nums2[j];
                    break;
                }else{
                    res[i]=-1;
                }
            }
        }
        return res;
    }

    public int[] maxStack(int[] nums1,int[] nums2){
        Map<Integer,Integer> map=new HashMap<>();
        Deque<Integer> stack=new ArrayDeque<>();
        for (int i = nums2.length-1; i>=0 ; i--) {
            int num=nums2[i];
            while (!stack.isEmpty()&&num>=stack.peek()){
                stack.pop();
            }
            map.put(num,stack.isEmpty()?-1:stack.peek());
            stack.push(num);
        }
        int[] res=new int[nums1.length];
        for (int i = 0; i <nums1.length ; i++) {
            res[i]=map.get(nums1[i]);
        }

        return res;
    }
}
